package uk.ac.aber.paws.client.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Vector;
import java.util.logging.Level;
import uk.ac.aber.paws.client.core.Initiator;
import uk.ac.aber.paws.client.core.PAWSClient;
import uk.ac.aber.paws.client.idlelogger.IdleLogger;
import uk.ac.aber.paws.client.net.SendMessage;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 16th August 2011
 * 
 * DBOperations.java
 * 
 * This class contains procedures relating to the DBCall queues that are in operation
 * within the PAWS Client.
 * 
 * a) Operations to process the DBCall queue
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class DBOperations {

	/**
	 * This procedure parses the cached DBCall queue. These DBCalls have previously
	 * failed and this procedure will periodically attempt to retransmit the database
	 * call.
	 */
	public static void parseQueuedDBCalls() {
		
		Vector<DBCall> cachedCalls = PAWSClient.SYSTEM_STATE.getCachedDBcalls();
		
		try {
		
			Initiator.LOG_FILE.log(Level.ALL,"Cached DB Calls = "+cachedCalls.toString());
			
			for (int i=0;i<cachedCalls.size();i++) { 
		
				DBCall object = PAWSClient.SYSTEM_STATE.getCachedDBcalls().get(i);
				
				object.setResponseRequired(false);
				
				if (SendMessage.sendDBCall(object) != null) {
					PAWSClient.SYSTEM_STATE.removeCachedDBCall(i);
				}
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * On application start up, this will transfer all cached DBCalls from file back into
	 * the data structure so that they are attempted to be retransmitted once again.
	 */
	public static void repopulateSavedDBCalls() {
		
		File[] fileList = (new File(PAWSClient.getConfig().getProperty("app.main.homedir")+PAWSClient.getConfig().getProperty("app.main.cachedir"))).listFiles();
		
		if (fileList.length > 0) {
			Initiator.LOG_FILE.log(Level.INFO,"Number of cached DB files to process = "+fileList.length);
		}
		
		for (int i=0;i<fileList.length;i++) {
			
			try {
				FileInputStream fis = new FileInputStream(fileList[i].getPath());
			
				ObjectInputStream input = new ObjectInputStream(fis);
				
				@SuppressWarnings("unchecked")
				Vector<DBCall> tmpVector = (Vector<DBCall>)input.readObject();
				
				Initiator.LOG_FILE.log(Level.INFO,"Number of cached DB calls to process = "+tmpVector.size());
				
				for (int j=0;j<tmpVector.size();j++) {
					
					DBCall object = (DBCall)tmpVector.get(j);
					
					object.setResponseRequired(false);
					
					if (SendMessage.sendDBCall(object) == null) {
						PAWSClient.SYSTEM_STATE.addCachedDBCall(object);
					}
				}
				
				input.close();
				fis.close();
				
				fileList[i].delete();
			}
			catch (Exception ex) {
				Initiator.LOG_FILE.log(Level.INFO,ex.toString());
			}
		}
		
	}
	/**
	 * On application exit, if there are cached DBCalls, then they must be saved to file
	 * so that they may be transmitted 
	 */
	public static void saveCheckDBCallsToFile() {
		
		if (PAWSClient.SYSTEM_STATE.getCachedDBcalls().size() > 0) {
			
			try {
				new File(PAWSClient.CONFIGURATION.getProperty("app.main.homedir")+IdleLogger.getMainConfig().getProperty("app.main.configdir")+IdleLogger.getMainConfig().getProperty("app.main.cachedir")).mkdirs();
				
				//FileOutputStream tmpFile = new FileOutputStream ("c:/program files/paws/cache/dbcalls.obj."+Calendar.getInstance().getTimeInMillis());
				FileOutputStream tmpFile = new FileOutputStream (PAWSClient.CONFIGURATION.getProperty("app.main.homedir")+IdleLogger.getMainConfig().getProperty("app.main.configdir")+IdleLogger.getMainConfig().getProperty("app.main.cachedir")+"dbcalls.obj."+Calendar.getInstance().getTimeInMillis());
			
				ObjectOutputStream output = new ObjectOutputStream(tmpFile);
				
				output.writeObject(PAWSClient.SYSTEM_STATE.getCachedDBcalls());
				
				output.close();
				tmpFile.close();
			}
			catch (Exception ex) {
				ex.printStackTrace();
			}
			
		}
	}

}
